<template>
    <Form ref="formItem" :model="formItem" :label-width="100" :rules="ruleValidate">
        <FormItem label="请假种类" prop="teacher_leave_kind">
            <Select v-model="formItem.teacher_leave_kind" >
                <Option v-for="item in DictionaryList" :value="item.dictionary_id" :key="item.dictionary_id">{{ item.dictionary_name.zh?item.dictionary_name.zh:item.dictionary_name.mn }}</Option>
            </Select>
        </FormItem>
        <FormItem label="请假时间" >
            <DatePicker type="datetimerange" :options="options3" format="yyyy-MM-dd HH:mm" :transfer="transfer" v-model="leavedate" @on-change="selDate" placeholder="请选择请假时间" style="width: 100%"></DatePicker>
        </FormItem>
        <FormItem label="请假天数" prop="leave_days">
            <Input v-model="formItem.leave_days" placeholder="请假天数"></Input>
        </FormItem>
        <FormItem label="是否调课" prop="whether_class">
            <Select v-model="formItem.whether_class" @on-change="whether">
                <Option :value="1" :key="1">是</Option>
                <Option :value="2" :key="2">否</Option>
            </Select>
        </FormItem>
        <FormItem label="调课安排" v-if="formItem.whether_class=='1'">
            <div class="cont-table" >
                <Select v-model="curriculumId" style="width:50%;padding-bottom:10px;" @on-change="formState">
                    <Option v-for="item in curriculumList" :value="item.id" :key="item.id">{{ item.name.zh?item.name.zh:item.name.mn }}</Option>
                </Select>
                <Table :columns="columns1" height="200" :data="courselist" :loading="tableload"></Table>
            </div>
        </FormItem>
        <FormItem label="教师请假原因">
            <Input v-model="formItem.teacher_leave_reason.zh" type="textarea" :autosize="{minRows: 2,maxRows: 4}" placeholder="请假原因"></Input>                                       
        </FormItem>
        <FormItem label="选择审核人">
            <div style="margin-bottom:3px">
                <Tag closable color="green" v-for="item in allPoles" :key="item.id" :name="item.id"  @on-close="delPople">{{item.teacher_name.zh?item.teacher_name.zh:item.teacher_name.mn}}</Tag>
            </div>
            <Poptip placement="bottom-start" width="400" :transfer="transfer" trigger="hover">
                <Button>添加审核人</Button>
                <div slot="content" style="padding:10px">
                    <Select placeholder="请选择职务" v-model="duties_id" style="display:block" @on-change="studentInfo">
                        <Option v-for="item in gradelist" :value="item.id" :key="item.id"> {{item.duties_name.zh?item.duties_name.zh:item.duties_name.mn}}</Option>            
                    </Select>
                    <Select placeholder="请选择审核人" v-model="formItem.examine_id" style="display:block">
                        <Option v-for="item in teacherlist" :value="item.user_id" :key="item.user_id"> {{item.teacher_name.zh?item.teacher_name.zh:item.teacher_name.mn}}</Option>            
                    </Select>
                    <Button type="primary" style="margin-top:10px" @click="addPeple">添加审核人</Button>
                </div>
            </Poptip>
        </FormItem>
        <FormItem>
            <Button type="primary" @click="submit('formItem')" :loading="btnload">{{infoId?'修改':'添加'}}</Button>
        </FormItem>
    </Form>
</template>

<script>
export default {
    props: {
        infoId:Number, 
    },
    data () {
        return {
            leavedate:[],
            curriculumId:null,
            curriculumList:[],
            duties_id:null,
            userlist:[],
            tableload:false,
            courselist:[],
            DictionaryList:[],
            teacherlist:[],
            gradelist:[],
            allPoles: [],
            transfer:true,
            options3: {
                disabledDate (date) {
                    return date && date.valueOf() < Date.now() - 86400000;
                }
            },
            formItem: {                    
                teacher_leave_id:this.infoId, 
                teacher_leave_kind:null,
                whether_class:'',
                teacher_leave_reason:{
                    zh:'',mn:'',en:'',
                },
                class:[],
                leave_days:'',
                start_time:'',
                end_time:'',
                examine_id: '',
            },
            time_status:'',
            btnload:false,
            addUrl:'api/leave/v1/teacher_leave/edit',
            editUrl:'api/leave/v1/teacher_leave/getone/',
            updateUrl:'api/leave/v1/teacher_leave/update/',
            ruleValidate: {
                // leave_days:[
                //     { required: true,type: 'number', message: '请输入请假天数', trigger: 'blur' }
                // ],
                whether_class: [
                    { required: true, type: 'number', message: '请选择是否调课', trigger: 'change' }
                ],
                examine_id: [
                    { required: true, type: 'number', message: '请选择审核人', trigger: 'change' }
                ],
                teacher_leave_kind: [
                    { required: true, type: 'number', message: '请选择请假种类', trigger: 'change' }
                ],
            },
            columns1:[
                {
                    title: '课程',				
                    align: 'center',
                    key:'course',
                },
                {
                    title: '教师',
                    align: 'center',
                    render: (h, params) => {
                        let ss=[]
                            params.row.teacher.forEach((item)=>{
                            ss.push(h('Option', {
                                props: {
                                    value:item.value,
                                    }
                                },item.label))
                            })
                        return h('Select',{
                            props:{
                                value:params.row.seleced_id ? params.row.seleced_id : '',//默认选中第一个（v-model）
                                clearable:true
                            },
                            on:{
                                'on-change':(value) => {
                                    let arr={
                                        user_id:value,
                                        course_arrange_id:params.row.course_arrange_id,
                                        cycle:params.row.cycle
                                    }
                                    if(this.formItem.class[params.index]&&this.formItem.class[params.index].user_id==arr.user_id){
                                        this.formItem.class[params.index]=arr
                                    }else if(value!=undefined){
                                        this.formItem.class.push(arr);
                                    }
                                },
                                'on-clear':()=>{
                                    if(this.infoId!=null){
                                        let a = this.formItem.class.findIndex(el=>el==this.formItem.class[params.index])
                                        let b = this.formItem.class.find((el,ind)=>ind==a)  
                                        b.user_id = ''
                                    }else{
                                        this.formItem.class.splice(this.formItem.class.findIndex(el=>el==this.formItem.class[params.index]),1)
                                    }
                                }
                            },
                        },ss);
                    },
                },
            ],
        }
    },
    methods: {
        /************************************************************
         * 处理时间
         ************************************************************/
        selDate(val){ 
            this.time_status = ''
            this.formItem.start_time = val[0] 
            this.formItem.end_time = val[1]  
            this.leavedays()  
        },
        leavedays(){
		
			
		if(this.formItem.start_time != null || formItem.end_time != null){
			let tim =new Date(this.formItem.end_time).getTime()  - new Date(this.formItem.start_time).getTime()
			let days=Math.floor(tim/(24*3600*1000))
			let leave1=tim%(24*3600*1000)    
			let hours=Math.floor(leave1/(3600*1000))  
			if(days>0){
				if(hours == 0){
					this.formItem.leave_days = days 
				}else if(hours<=6){
					this.formItem.leave_days = days + 0.5
				}else{
					this.formItem.leave_days = days  +1
				}
			}else if(days == 0){
				if(hours == 0){
					this.$Message.error("请重新选择请假时间!");
					this.formItem.leave_days = null
				}else if(hours<=6){
					this.formItem.leave_days =0.5
				}else{
					this.formItem.leave_days = 1
				}
			}else if(days == NaN){
				this.formItem.leave_days =null
			}else{
				this.$Message.error("请重新选择请假时间!");
				this.formItem.leave_days =null
			}
			
		}
	},
        /************************************************************
         * 选择是否调课
         ************************************************************/      
        whether(val){   
            if(val == 1){
                this.selectcourse()
            }
        },
        /************************************************************
         * 获取课程列表
         ************************************************************/
        selectcourse(){
            if (this.formItem.start_time !='' && this.formItem.end_time !='' && this.formItem.whether_class!='') {
                this.tableload = true;
                this.courselist = []
                this.$http.get(`api/leave/v1/teacher_leave/course?start_time=${this.formItem.start_time}&end_time=${this.formItem.end_time}`).then(response => {
                    if (response.data.length != 0){
                        response.data.forEach(el=>{
                            this.courselist.push({
                                course:`${el.date} ${el.week_id.dictionary_name.zh} ${el.class_type.name.zh} ${el.course_id.course_name.zh}`,
                                course_id:el.course_id.id,
                                teacher:[],
                                seleced_id:'',
                                course_arrange_id:el.course_arrange_id,
                                cycle:el.cycle,
                            })
                            let arr = [];
                            arr.push({
                                id:el.course_id.id,
                                name:el.course_id.course_name.zh,
                            })
                            this.curriculumList = arr.filter(item=> item.id==item.id)
                        })
                        this.formState(this.curriculumList[0].id)
                        this.tableload = false;
                    }else{
                        this.tableload = false;				  
                    }                    
            }).catch(err => {
                if (err.code && err.code == 422) {
                    this.$Message.error(err.message);
                }
                this.tableload = false;		
            })
        }
        },
        /************************************************************
         * 选择课程获取教师
         ************************************************************/
        formState(val){
            if(val!=null){
                this.curriculumId = val
                this.course(val)
            }
        },
        /************************************************************
         * 获取教师
         ************************************************************/
        course(id){   
            this.$http.get(`api/leave/v1/teacher_leave/teacher/${id}`).then((response) => {
                let ss = []
                response.data.forEach(item=>{
                    ss.push({
                        value:item.user_id,
                        label:item.teacher_name.zh?item.teacher_name.zh:item.teacher_name.mn
                    })
                })
                this.courselist.forEach(el=>{
                    el.teacher=ss
                })
            }).catch(err => {
                if (err.code && err.code == 422) {
                    this.$Message.error(err.message);
                }
            })
        },
        /************************************************************
         * 加载职务、请假分类
         ************************************************************/
        load() {  
            this.$http.get("api/user/v1/get/duties/list").then(response => {
                this.gradelist = response.data;
            }).catch(err => {
                if (err.code && err.code == 422) {
                    this.$Message.error(err.message);
                }
            })

            this.$http.get('api/dictionary/v1/dictionary/pidquerys?teacher_leave_kind').then(val=>{ 
                this.DictionaryList=val.data.teacher_leave_kind               
            }).catch(err => {
                if (err.code && err.code == 422) {
                    this.$Message.error(err.message);
                }
            })
        },
        /************************************************************
         * 点击职务
         ************************************************************/
        studentInfo(value) {
            this.teacherlist=[]
            this.$http.get(`api/user/v1/get/teacher/user/list?duties_id=[${value}]`).then(val => {
                this.teacherlist = val.data;
            }).catch(err => {
                if (err.code && err.code == 422) {
                    this.$Message.error(err.message);
                }
            })
        },
        /************************************************************
         * 添加部门老师
         ************************************************************/
        addPeple() {
            if(this.formItem.examine_id!=null){
                if(this.teacherlist.length!=0){
                    let obj = this.teacherlist.find(item => item.user_id == this.formItem.examine_id);
                    this.allPoles = [];
                    this.allPoles.push(obj);
                }
            }
        },
        /************************************************************
         * 删除审核人
         ************************************************************/
        delPople(event, name) {
			let i = this.allPoles.findIndex((item)=> {
				return item.id == name
			})
            this.allPoles.splice(i, 1);
        },
        /************************************************************
         * 提交
         ************************************************************/
        submit (name) {
            this.$refs[name].validate((valid) => {
                if (valid) {
                    
                    if(this.formItem.start_time!='' && this.formItem.end_time!=''){
                        if(this.formItem.examine_id!=''){
                            if (this.infoId!=null) {
                                this.editSubmit ()
                            } else {
                                if(this.formItem.whether_class == 1){
                                    if(this.formItem.class.length!=0){
                                        this.addSubmit ()
                                    }else{
                                        this.$Message.error('请选择调课信息');
                                        this.btnload = false
                                    }
                                }else{
                                    this.addSubmit ()
                                }
                            }
                        }else{
                            this.$Message.error('请选择审核人');
                            this.btnload = false
                        }
                    }else{
                        this.$Message.error('请选择请假时间');
                        this.btnload = false
                    }
                } else {
                    this.$Message.error('验证失败');
                    this.btnload = false 
                }
            })
        },
        
        /************************************************************
         * 执行添加数据
         ************************************************************/
        addSubmit () {    
            this.btnload = true   
            this.$http.post(this.addUrl,this.formItem).then(val => {
                this.$Message.success(val.message);
                this.$emit('requery',true);
                this.btnload = false
            }).catch(err => {
                if (err.code && err.code == 422) {
                    this.$Message.error(err.message);
                }
                this.btnload = false 
            })
        },
        
        /************************************************************
         * 执行修改数据
         ************************************************************/
        editSubmit () {
            this.btnload = true
            // this.formItem.class.filter(el=>el.user_id == undefined)  
            // console.log(this.formItem.class)     
            // return  
            this.$http.put(`${this.updateUrl}${this.infoId}`,this.formItem).then(val=>{
                this.$Message.success(val.message);
                this.$emit('requery',true);
                this.btnload = false 
            }).catch(err => {
                if (err.code && err.code == 422) {
                    this.$Message.error(err.message);
                }
                this.btnload = false 
            })
        },
        
        /************************************************************
         * 单条数据查询（修改）
         ************************************************************/
        infodata(){
            
            this.$http.get(`${this.editUrl}${this.infoId}`).then(val=>{     
                let infoOld = JSON.parse(JSON.stringify(val.data)) 
                this.time_status = 'edit'
                this.teacher_leave_id = parseInt(infoOld.teacher_leave_id)                                     
                this.formItem.teacher_leave_kind = parseInt(infoOld.teacher_leave_kind)
                this.formItem.whether_class = parseInt(infoOld.whether_class)
                this.formItem.start_time = infoOld.start_time
                this.formItem.end_time = infoOld.end_time
                this.formItem.teacher_leave_reason= infoOld.teacher_leave_reason
                this.leavedate =[infoOld.start_time,infoOld.end_time]
                if(infoOld.leave_days!=''){
                    this.formItem.leave_days = infoOld.leave_days
                }else{
                    this.formItem.leave_days = '0'
                }
                this.formItem.examine_id = parseInt(infoOld.examine.examine_id)   
                this.allPoles.push({
                    id:infoOld.examine.examine_id,    
                    teacher_name:infoOld.examine.teacher.teacher_name,
                })     
                if(infoOld.whether_class==1){
                    this.editcourse(infoOld.start_time,infoOld.end_time,infoOld.teacher_leave_id)                  
                }
            }).catch(err => {
                console.log(err);
            })
        },
        /************************************************************
         * 修改时的课程
         ************************************************************/
        editcourse(star,end,id){
            this.courselist = []
            this.$http.get(`api/leave/v1/teacher_leave/course?start_time=${star}&end_time=${end}&teacher_leave_id=${id}`).then((response) => {
                let arr = [];
                response.data.forEach(el=>{
                    this.courselist.push({
                        course:`${el.date} ${el.week_id.dictionary_name.zh} ${el.class_type.name.zh} ${el.course_id.course_name.zh}`,
                        course_id:el.course_id.id,
                        teacher:[],
                        seleced_id:el.teacher.user_id,
                        course_arrange_id:el.course_arrange_id,
                        cycle:el.cycle,
                    })
                    
                    if(el.teacher.user_id!=null){
                        arr.push({
                            user_id:el.teacher.user_id,
                            course_arrange_id:el.course_arrange_id,
                            cycle:el.cycle,
                        })
                    }
                    
                })
                this.formItem.class = arr
                this.curriculumList.push({
                    id:response.data[0].course_id.id,
                    name:response.data[0].course_id.course_name.zh,
                })              
                this.curriculumId = response.data[0].course_id.id
                this.formState(this.curriculumId)
            });
        },
    },
    created () {
        this.load();
        if (this.infoId!=null){            
            this.infodata ()
        } 
    },
    watch:{
        'formItem.end_time'(val,data){
            if(val != data && this.time_status != 'edit'){
                this.selectcourse()
            }
        }
	},
}
</script>